package com.gewu.pm.ui.activity.promotion;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.bean.GoodsBean;
import com.gewu.pm.ui.activity.order.AddGoodsActivity;
import com.gewu.pm.ui.dialog.CustomTimeDialog;
import com.gewu.pm.ui.dialog.SelectionListDialog;
import com.gewu.pm.utils.TextStarUtils;
import com.gewu.pm.utils.eventbus.EventBean;
import com.gewu.pm.utils.eventbus.EventBusUtil;
import com.gewu.pm.utils.eventbus.EventCode;
import com.hjq.base.BaseDialog;
import com.hjq.widget.view.ClearEditText;

import java.util.ArrayList;
import java.util.List;

/**
 * 创建买赠活动页面
 */
public final class PromotionCreateActivity extends AppActivity {

    // 基本信息
    private TextView mActivityNameLabel;
    private ClearEditText mActivityNameEdit;
    private ClearEditText mActivityDetailEdit;
    private TextView mOrderDateLabel;
    private TextView mOrderDateValue;
    private TextView mActivityTypeLabel;
    private TextView mActivityTypeValue;

    // 客户范围
    private TextView mPromotionTargetLabel;
    private TextView mPromotionTargetValue;
    private TextView mCustomerScopeLabel;
    private TextView mCustomerScopeEdit;

    // 促销规则
    private TextView mPromotionTypeLabel;
    private TextView mPromotionTypeValue;
    private TextView mGiftMethodLabel;
    private TextView mGiftMethodValue;
    private RelativeLayout mLayoutConditionInput;  // 条件输入布局（满赠金额/满赠数量）
    private TextView mConditionLabel;
    private EditText mConditionEdit;
    private TextView mConditionUnit;
    private TextView mGiftRuleLabel;
    private TextView mGiftRuleValue;

    // 促销主品
    private RelativeLayout mLayoutMainProduct;
    private TextView mMainProductTitle;
    private TextView mMainProductCount;
    private TextView mMainProductTotal;
    private TextView mSelectMainProductButton;

    // 促销赠品
    private RelativeLayout mLayoutGiftProduct;
    private TextView mGiftProductTitle;
    private TextView mGiftProductCount;
    private TextView mGiftProductTotal;
    private TextView mSelectGiftProductButton;

    // 提交按钮
    private TextView mSubmitButton;

    // 数据
    private int mMainProductVarietyCount = 0;  // 主品品种数量
    private int mMainProductTotalCount = 0;   // 主品商品总数
    private int mGiftProductVarietyCount = 0;  // 赠品品种数量
    private int mGiftProductTotalCount = 0;   // 赠品商品总数
    private List<com.gewu.pm.bean.GoodsBean> mMainProductList = new ArrayList<>();  // 主品列表
    private List<com.gewu.pm.bean.GoodsBean> mGiftProductList = new ArrayList<>();  // 赠品列表

    public static void start(Context context) {
        Intent intent = new Intent(context, PromotionCreateActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.create_promotion_activity;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setTitle("创建买赠活动");

        // 基本信息
        mActivityNameLabel = findViewById(R.id.tv_activity_name_label);
        mActivityNameEdit = findViewById(R.id.et_activity_name);
        mActivityDetailEdit = findViewById(R.id.et_activity_detail);
        mOrderDateLabel = findViewById(R.id.tv_order_date_label);
        mOrderDateValue = findViewById(R.id.tv_order_date_value);
        mActivityTypeLabel = findViewById(R.id.tv_activity_type_label);
        mActivityTypeValue = findViewById(R.id.tv_activity_type_value);

        // 客户范围
        mPromotionTargetLabel = findViewById(R.id.tv_promotion_target_label);
        mPromotionTargetValue = findViewById(R.id.tv_promotion_target_value);
        mCustomerScopeLabel = findViewById(R.id.tv_customer_scope_label);
        mCustomerScopeEdit = findViewById(R.id.et_customer_scope);

        // 促销规则
        mPromotionTypeLabel = findViewById(R.id.tv_promotion_type_label);
        mPromotionTypeValue = findViewById(R.id.tv_promotion_type_value);
        mGiftMethodLabel = findViewById(R.id.tv_gift_method_label);
        mGiftMethodValue = findViewById(R.id.tv_gift_method_value);
        mLayoutConditionInput = findViewById(R.id.layout_condition_input);
        mConditionLabel = findViewById(R.id.tv_condition_label);
        mConditionEdit = findViewById(R.id.et_condition);
        mConditionUnit = findViewById(R.id.tv_condition_unit);
        mGiftRuleLabel = findViewById(R.id.tv_gift_rule_label);
        mGiftRuleValue = findViewById(R.id.tv_gift_rule_value);

        // 促销主品
        mLayoutMainProduct = findViewById(R.id.layout_main_product);
        mMainProductTitle = findViewById(R.id.tv_main_product_title);
        mMainProductCount = findViewById(R.id.tv_main_product_count);
        mMainProductTotal = findViewById(R.id.tv_main_product_total);
        mSelectMainProductButton = findViewById(R.id.btn_select_main_product);

        // 促销赠品
        mLayoutGiftProduct = findViewById(R.id.layout_gift_product);
        mGiftProductTitle = findViewById(R.id.tv_gift_product_title);
        mGiftProductCount = findViewById(R.id.tv_gift_product_count);
        mGiftProductTotal = findViewById(R.id.tv_gift_product_total);
        mSelectGiftProductButton = findViewById(R.id.btn_select_gift_product);

        // 提交按钮
        mSubmitButton = findViewById(R.id.tv_bottom_button);

        // 设置必填标记
        TextStarUtils.setRequiredText(mActivityNameLabel, "促销活动名称");
        TextStarUtils.setRequiredText(mOrderDateLabel, "订单日期");
        TextStarUtils.setRequiredText(mActivityTypeLabel, "活动类型");
        TextStarUtils.setRequiredText(mPromotionTargetLabel, "促销对象");
        TextStarUtils.setRequiredText(mCustomerScopeLabel, "客户范围");
        TextStarUtils.setRequiredText(mPromotionTypeLabel, "促销类型");
        TextStarUtils.setRequiredText(mMainProductTitle, "促销主品");
        TextStarUtils.setRequiredText(mGiftProductTitle, "促销赠品");

        // 设置点击事件
        setOnClickListener(mOrderDateValue, mActivityTypeValue, mPromotionTargetValue,
                mPromotionTypeValue, mGiftMethodValue, mGiftRuleValue,
                mLayoutMainProduct, mSelectMainProductButton,
                mLayoutGiftProduct, mSelectGiftProductButton, mSubmitButton,mCustomerScopeEdit);
    }

    @Override
    protected void initData() {
        // 初始隐藏促销主品和赠品
        mLayoutMainProduct.setVisibility(View.GONE);
        mLayoutGiftProduct.setVisibility(View.GONE);
        mLayoutConditionInput.setVisibility(View.GONE);
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        super.onClick(view);
        int id = view.getId();
        if (id == R.id.tv_order_date_value) {
            // 选择订单日期
            new CustomTimeDialog.Builder(getContext())
                    .setListener(new CustomTimeDialog.OnListener() {
                        @Override
                        public void onSelected(BaseDialog dialog, int startYear, int startMonth, int startDay,
                                               int endYear, int endMonth, int endDay) {
                            // 格式化日期显示
                            String startDate = startYear + "-" + String.format("%02d", startMonth) + "-" + String.format("%02d", startDay);
                            String endDate = endYear + "-" + String.format("%02d", endMonth) + "-" + String.format("%02d", endDay);
                            String timeRange = startDate + " 至 " + endDate;

                            // 更新 FilterBar 显示的日期文本
                            mOrderDateValue.setText(timeRange);
                            mOrderDateValue.setTextColor(getResources().getColor(R.color.cb3));
                            toast("已选择时间范围：" + timeRange);
                        }
                    })
                    .show();
        } else if (id == R.id.tv_activity_type_value) {
            // 选择活动类型
            toast("选择活动类型");
            // TODO: 打开活动类型选择
        } else if (id == R.id.tv_promotion_target_value) {// 选择促销对象
            List<String> options = new ArrayList<>();
            options.add("终端");
            options.add("配送商");
            options.add("销售区域");

            new SelectionListDialog.Builder(this)
                    .setTitle("促销对象")
                    .setDataList(options)
                    .setListener(new SelectionListDialog.OnListener() {
                        @Override
                        public void onSelected(BaseDialog dialog, String selectedItem, int position) {
                            mPromotionTargetValue.setText(selectedItem);
                            mPromotionTargetValue.setTextColor(getResources().getColor(R.color.cb3));
                        }
                    })
                    .show();
        } else if (id == R.id.et_customer_scope) {// 客服范围
            toast("根据选择的促销对象而定");

        } else if (id == R.id.tv_promotion_type_value) {
            // 选择促销类型
            showPromotionTypeDialog();
        } else if (id == R.id.tv_gift_method_value) {
            // 选择赠送方式
            toast("选择赠送方式");
            // TODO: 打开赠送方式选择
        } else if (id == R.id.tv_gift_rule_value) {
            // 选择满送规则
            toast("选择满送规则");
            // TODO: 打开满送规则选择
        } else if (id == R.id.btn_select_main_product) {
            // 选择促销主品 - 跳转到选择商品页面，传递已选商品
            AddGoodsActivity.start(this, 1, mMainProductList);  // type=1表示促销主品
        } else if (id == R.id.layout_main_product) {
            // 点击促销主品Item - 跳转到编辑页面
            if (mMainProductVarietyCount > 0 && !mMainProductList.isEmpty()) {
                PromotionProductActivity.start(this, 1, mMainProductList);
            }
        } else if (id == R.id.btn_select_gift_product) {
            // 选择促销赠品 - 跳转到选择商品页面，传递已选商品
            AddGoodsActivity.start(this, 2, mGiftProductList);  // type=2表示促销赠品
        } else if (id == R.id.layout_gift_product) {
            // 点击促销赠品Item - 跳转到编辑页面
            if (mGiftProductVarietyCount > 0 && !mGiftProductList.isEmpty()) {
                PromotionProductActivity.start(this, 2, mGiftProductList);
            }
        } else if (id == R.id.tv_bottom_button) {
            // 提交
            submit();
        }
    }

    /**
     * 显示促销类型选择对话框
     */
    private void showPromotionTypeDialog() {
        List<String> options = new ArrayList<>();
        options.add("满赠金额");
        options.add("满赠数量");

        new SelectionListDialog.Builder(this)
                .setTitle("选择促销类型")
                .setDataList(options)
                .setListener(new SelectionListDialog.OnListener() {
                    @Override
                    public void onSelected(BaseDialog dialog, String selectedItem, int position) {
                        mPromotionTypeValue.setText(selectedItem);
                        updateConditionInput(selectedItem);
                    }
                })
                .show();
    }

    /**
     * 更新条件输入布局
     */
    private void updateConditionInput(String promotionType) {
        mLayoutConditionInput.setVisibility(View.VISIBLE);

        if ("满赠金额".equals(promotionType)) {
            mConditionLabel.setText("单笔订单主品订购金额满");
            mConditionUnit.setText("元，即送出全部赠品");
        } else if ("满赠数量".equals(promotionType)) {
            mConditionLabel.setText("单笔订单主品订购数量满");
            mConditionUnit.setText("盒，即送出全部赠品");
        }
    }

    /**
     * 提交
     */
    private void submit() {
        // TODO: 验证必填项

        toast("提交成功");

        // 发送事件通知促销管理页面刷新
        EventBusUtil.sendEvent(new EventBean<>(EventCode.PROMOTION_CREATED));

        // 关闭当前页面
        finish();
    }

    @Override
    protected boolean isRegisteredEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(EventBean event) {
        if (event.getCode() == EventCode.PROMOTION_GOODS_CHANGED) {
            // 接收商品变更事件
            Object data = event.getData();
            if (data instanceof Object[]) {
                Object[] eventData = (Object[]) data;
                int type = (int) eventData[0];  // 1-主品，2-赠品
                List<GoodsBean> goodsList = (List<GoodsBean>) eventData[1];  // 商品列表

                if (type == 1) {
                    // 更新促销主品
                    mMainProductList = goodsList;
                    updateMainProduct(goodsList);
                } else if (type == 2) {
                    // 更新促销赠品
                    mGiftProductList = goodsList;
                    updateGiftProduct(goodsList);
                }
            }
        }
    }

    /**
     * 更新促销主品显示
     */
    private void updateMainProduct(List<GoodsBean> goodsList) {
        // 计算品种数量和商品总数
        int varietyCount = 0;
        int totalCount = 0;
        for (GoodsBean goods : goodsList) {
            if (goods.getQuantity() > 0) {
                varietyCount++;
                totalCount += goods.getQuantity();
            }
        }

        mMainProductVarietyCount = varietyCount;
        mMainProductTotalCount = totalCount;

        if (mMainProductVarietyCount > 0) {
            // 显示促销主品Item
            mLayoutMainProduct.setVisibility(View.VISIBLE);
            mMainProductCount.setText("品种数量：" + mMainProductVarietyCount);
            mMainProductTotal.setText("商品总数：" + mMainProductTotalCount);
        } else {
            // 隐藏促销主品Item
            mLayoutMainProduct.setVisibility(View.GONE);
        }
    }

    /**
     * 更新促销赠品显示
     */
    private void updateGiftProduct(List<GoodsBean> goodsList) {
        // 计算品种数量和商品总数
        int varietyCount = 0;
        int totalCount = 0;
        for (GoodsBean goods : goodsList) {
            if (goods.getQuantity() > 0) {
                varietyCount++;
                totalCount += goods.getQuantity();
            }
        }

        mGiftProductVarietyCount = varietyCount;
        mGiftProductTotalCount = totalCount;

        if (mGiftProductVarietyCount > 0) {
            // 显示促销赠品Item
            mLayoutGiftProduct.setVisibility(View.VISIBLE);
            mGiftProductCount.setText("品种数量：" + mGiftProductVarietyCount);
            mGiftProductTotal.setText("商品总数：" + mGiftProductTotalCount);
        } else {
            // 隐藏促销赠品Item
            mLayoutGiftProduct.setVisibility(View.GONE);
        }
    }
}

